import re
from datetime import datetime
from typing import Dict

class TextParser:
    """文本解析器，用于解析问卷报告文本"""
    
    @staticmethod
    def parse_txt_to_json(content: str) -> Dict:
        """解析TXT文件内容并转换为JSON格式"""
        data = {}
        
        # 检查是否为PSQI睡眠质量评估报告
        if 'PSQI睡眠质量评估结果报告' in content:
            return TextParser.parse_psqi_report(content)
        
        # 原有的解析逻辑（用于其他问卷）
        # 解析问答编号
        survey_id_match = re.search(r'问答编号：(\w+)', content)
        if survey_id_match:
            data['surveyId'] = survey_id_match.group(1)
        
        # 解析生成时间
        time_match = re.search(r'生成时间：(\d{4}/\d{1,2}/\d{1,2} \d{1,2}:\d{1,2}:\d{1,2})', content)
        if time_match:
            time_str = time_match.group(1)
            # 转换为ISO格式
            dt = datetime.strptime(time_str, '%Y/%m/%d %H:%M:%S')
            data['createdAt'] = dt.isoformat() + 'Z'
        
        # 解析记录人信息
        recorder_name_match = re.search(r'记录人姓名：(.+)', content)
        if recorder_name_match:
            data['recorderName'] = recorder_name_match.group(1).strip()
        
        recorder_position_match = re.search(r'记录人职务/身份：(.+)', content)
        if recorder_position_match:
            data['recorderPosition'] = recorder_position_match.group(1).strip()
        
        recorder_institution_match = re.search(r'所属机构：(.+)', content)
        if recorder_institution_match:
            data['recorderInstitution'] = recorder_institution_match.group(1).strip()
        
        recorder_contact_match = re.search(r'联系方式：(.+)', content)
        if recorder_contact_match:
            data['recorderContact'] = recorder_contact_match.group(1).strip()
        
        record_time_match = re.search(r'记录时间：(\d{4}/\d{1,2}/\d{1,2} \d{1,2}:\d{1,2}:\d{1,2})', content)
        if record_time_match:
            data['recordTime'] = record_time_match.group(1)
        
        # 解析被评估人信息
        patient_name_match = re.search(r'姓名：(.+)', content)
        if patient_name_match:
            data['patientName'] = patient_name_match.group(1).strip()
        
        age_match = re.search(r'年龄：(\d+)岁', content)
        if age_match:
            data['age'] = int(age_match.group(1))
        
        gender_match = re.search(r'性别：(.+)', content)
        if gender_match:
            gender = gender_match.group(1).strip()
            data['gender'] = '男' if '男' in gender else '女'
        
        height_match = re.search(r'身高：(\d+(?:\.\d+)?)cm', content)
        if height_match:
            data['height'] = float(height_match.group(1))
        
        weight_match = re.search(r'体重：(\d+(?:\.\d+)?)kg', content)
        if weight_match:
            data['weight'] = float(weight_match.group(1))
        
        phone_match = re.search(r'联系电话：(.+)', content)
        if phone_match:
            data['phone'] = phone_match.group(1).strip()
        
        # 解析备注
        remarks_match = re.search(r'备注：(.+)', content)
        if remarks_match:
            data['remarks'] = remarks_match.group(1).strip()
        
        # 解析评估结果
        score_match = re.search(r'总分：(\d+)/5', content)
        if score_match:
            data['totalScore'] = int(score_match.group(1))
        
        diagnosis_match = re.search(r'诊断结果：(.+)', content)
        if diagnosis_match:
            data['diagnosis'] = diagnosis_match.group(1).strip()
        
        # 解析原始评估数据
        # 体重下降
        weight_loss_match = re.search(r'体重下降：(.+)', content)
        if weight_loss_match:
            data['weightLoss'] = 1 if '是' in weight_loss_match.group(1) else 0
        
        # 行走时间 - 从详细结果中判断阳性/阴性
        walk_result_match = re.search(r'2\. 行走时间：.*?\((.+?)\)', content)
        if walk_result_match:
            data['walkTime'] = 1 if '阳性' in walk_result_match.group(1) else 0
        else:
            data['walkTime'] = 0
        
        # 握力 - 从详细结果中判断阳性/阴性
        grip_result_match = re.search(r'3\. 握力：.*?\((.+?)\)', content)
        if grip_result_match:
            data['gripStrength'] = 1 if '阳性' in grip_result_match.group(1) else 0
        else:
            data['gripStrength'] = 0
        
        # 体力活动 - 从详细结果中判断阳性/阴性
        activity_result_match = re.search(r'4\. 体力活动：.*?\((.+?)\)', content)
        if activity_result_match:
            data['physicalActivity'] = 1 if '阳性' in activity_result_match.group(1) else 0
        else:
            data['physicalActivity'] = 0
        
        # 疲乏评分
        fatigue1_match = re.search(r'疲乏评分1：(\d+)分', content)
        if fatigue1_match:
            data['fatigue1'] = int(fatigue1_match.group(1))
        else:
            data['fatigue1'] = 0
        
        fatigue2_match = re.search(r'疲乏评分2：(\d+)分', content)
        if fatigue2_match:
            data['fatigue2'] = int(fatigue2_match.group(1))
        else:
            data['fatigue2'] = 0
        
        return data
    
    @staticmethod
    def parse_psqi_report(content: str) -> Dict:
        """专门解析PSQI睡眠质量评估报告"""
        data = {}
        
        # 解析问答编号
        survey_id_match = re.search(r'问答编号：(\w+)', content)
        if survey_id_match:
            data['surveyId'] = survey_id_match.group(1)
        
        # 解析生成时间
        time_match = re.search(r'生成时间：(\d{4}/\d{1,2}/\d{1,2} \d{1,2}:\d{1,2}:\d{1,2})', content)
        if time_match:
            time_str = time_match.group(1)
            dt = datetime.strptime(time_str, '%Y/%m/%d %H:%M:%S')
            data['createdAt'] = dt.isoformat() + 'Z'
        
        # 解析记录人信息
        recorder_name_match = re.search(r'记录人姓名：(.+)', content)
        if recorder_name_match:
            data['recorderName'] = recorder_name_match.group(1).strip()
        
        recorder_position_match = re.search(r'记录人职务/身份：(.+)', content)
        if recorder_position_match:
            data['recorderPosition'] = recorder_position_match.group(1).strip()
        
        recorder_institution_match = re.search(r'所属机构：(.+)', content)
        if recorder_institution_match:
            data['recorderInstitution'] = recorder_institution_match.group(1).strip()
        
        recorder_contact_match = re.search(r'联系方式：(.+)', content)
        if recorder_contact_match:
            data['recorderContact'] = recorder_contact_match.group(1).strip()
        
        record_time_match = re.search(r'记录时间：(\d{4}/\d{1,2}/\d{1,2} \d{1,2}:\d{1,2}:\d{1,2})', content)
        if record_time_match:
            data['recordTime'] = record_time_match.group(1)
        
        # 解析被评估人信息
        patient_name_match = re.search(r'姓名：(.+)', content)
        if patient_name_match:
            data['patientName'] = patient_name_match.group(1).strip()
        
        age_match = re.search(r'年龄：(\d+)岁', content)
        if age_match:
            data['age'] = int(age_match.group(1))
        
        gender_match = re.search(r'性别：(.+)', content)
        if gender_match:
            data['gender'] = gender_match.group(1).strip()
        
        phone_match = re.search(r'联系电话：(.+)', content)
        if phone_match:
            data['phone'] = phone_match.group(1).strip()
        
        remarks_match = re.search(r'备注：(.+)', content)
        if remarks_match:
            data['remarks'] = remarks_match.group(1).strip()
        
        # 解析PSQI评估结果
        total_score_match = re.search(r'总分：(\d+)/21', content)
        if total_score_match:
            data['totalScore'] = int(total_score_match.group(1))
        
        diagnosis_match = re.search(r'诊断结果：(.+)', content)
        if diagnosis_match:
            data['diagnosis'] = diagnosis_match.group(1).strip()
        
        # 解析睡眠习惯数据
        bedtime_match = re.search(r'就寝时间：(.+)', content)
        if bedtime_match:
            data['bedtime'] = bedtime_match.group(1).strip()
        
        sleep_latency_match = re.search(r'入睡时间：(\d+)分钟', content)
        if sleep_latency_match:
            data['sleepLatencyMinutes'] = int(sleep_latency_match.group(1))
        
        wake_time_match = re.search(r'起床时间：(.+)', content)
        if wake_time_match:
            data['wakeTime'] = wake_time_match.group(1).strip()
        
        sleep_duration_match = re.search(r'实际睡眠时间：([\d.]+)小时', content)
        if sleep_duration_match:
            data['sleepDuration'] = float(sleep_duration_match.group(1))
        
        # 解析睡眠质量评分
        sleep_quality_match = re.search(r'主观睡眠质量：(\d+)分', content)
        if sleep_quality_match:
            data['sleepQuality'] = int(sleep_quality_match.group(1))
        
        # 解析各组件得分 - 只匹配PSQI组件名称
        psqi_components = [
            '主观睡眠质量', '入睡时间', '睡眠时间', '睡眠效率', 
            '睡眠干扰', '催眠药物的使用', '日间功能障碍'
        ]
        
        for component_name in psqi_components:
            pattern = rf'{re.escape(component_name)}：(\d+)/(\d+)'
            match = re.search(pattern, content)
            if match:
                score = int(match.group(1))
                max_score = int(match.group(2))
                data[f'{component_name}_score'] = score
                data[f'{component_name}_maxScore'] = max_score
        
        return data
    
    @staticmethod
    def validate_survey_data(data: Dict) -> bool:
        """验证解析后的问卷数据是否完整"""
        required_fields = [
            'surveyId', 'patientName', 'age', 'gender',
            'weightLoss', 'walkTime', 'gripStrength', 'physicalActivity', 'fatigue1'
        ]
        
        for field in required_fields:
            if field not in data or data[field] is None:
                return False
        
        return True
    
    @staticmethod
    def extract_survey_metadata(content: str) -> Dict:
        """提取问卷元数据信息"""
        metadata = {}
        
        # 提取问卷类型
        if 'Fried衰弱评估' in content:
            metadata['survey_type'] = 'frailty_assessment'
            metadata['survey_name'] = 'Fried衰弱评估问卷'
        
        # 提取版本信息（如果有）
        version_match = re.search(r'版本：([\d\.]+)', content)
        if version_match:
            metadata['version'] = version_match.group(1)
        
        # 提取生成时间
        time_match = re.search(r'生成时间：(\d{4}/\d{1,2}/\d{1,2} \d{1,2}:\d{1,2}:\d{1,2})', content)
        if time_match:
            metadata['generated_at'] = time_match.group(1)
        
        return metadata